<?php
namespace api\models;

use Yii;
use yii\filters\RateLimitInterface;


class User extends \common\models\User implements  RateLimitInterface
{



  // 返回某一时间允许请求的最大数量，比如设置10秒内最多5次请求（小数量方便我们模拟测试）
  public  function getRateLimit($request, $action){
    return [5, 10];
  }

  // 回剩余的允许的请求和相应的UNIX时间戳数 当最后一次速率限制检查时
  public  function loadAllowance($request, $action){
    return [$this->allowance, $this->allowance_updated_at];
  }

  // 保存允许剩余的请求数和当前的UNIX时间戳
  public  function saveAllowance($request, $action, $allowance, $timestamp){
    $this->allowance = $allowance;
    $this->allowance_updated_at = $timestamp;
    $this->save();
  }
  public static function findIdentityByAccessToken($token, $type = null)
  {

    // 如果token无效的话，
    if(!static::apiTokenIsValid($token)) {
      throw new \yii\web\UnauthorizedHttpException("token is invalid.");
    }

    return static::findOne(['access_token' => $token, 'status' => self::STATUS_ACTIVE]);
    // throw new NotSupportedException('"findIdentityByAccessToken" is not implemented.');
  }


  /**
   * 生成 api_token
   */
  public function generateApiToken()
  {
    $this->access_token = Yii::$app->security->generateRandomString() . '_' . time();
  }
  public function loginByAccessToken(){

  }

  /**
   * 校验api_token是否有效
   */
  public static function apiTokenIsValid($token)
  {
    if (empty($token)) {
      return false;
    }

    $timestamp = (int) substr($token, strrpos($token, '_') + 1);
    $expire = Yii::$app->params['user.apiTokenExpire'];
    return $timestamp + $expire >= time();
  }


}
